package com.yzx.lifeassistants.activity;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.pedant.SweetAlert.SweetAlertDialog;

import com.balysv.materialripple.MaterialRippleLayout;
import com.bmob.BmobProFile;
import com.bmob.btp.callback.UploadBatchListener;
import com.github.jjobes.slidedatetimepicker.SlideDateTimeListener;
import com.github.jjobes.slidedatetimepicker.SlideDateTimePicker;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.rengwuxian.materialedittext.validation.METValidator;
import com.weiwangcn.betterspinner.library.material.MaterialBetterSpinner;
import com.yzx.lifeassistants.GlobalParams;
import com.yzx.lifeassistants.R;
import com.yzx.lifeassistants.adapter.EditGridAdapter;
import com.yzx.lifeassistants.adapter.MyArrayAdapter;
import com.yzx.lifeassistants.base.BaseActivity;
import com.yzx.lifeassistants.bean.FindThing;
import com.yzx.lifeassistants.bean.ImageItem;
import com.yzx.lifeassistants.common.CommonConstant;
import com.yzx.lifeassistants.utils.DensityUtils;
import com.yzx.lifeassistants.utils.FileUtils;
import com.yzx.lifeassistants.utils.ImageUtils;
import com.yzx.lifeassistants.utils.LogcatUtils;
import com.yzx.lifeassistants.utils.ToastUtils;
import com.yzx.lifeassistants.utils.VerifyUtils;
import com.yzx.lifeassistants.view.widget.CircularLoadingDialog;
import com.yzx.lifeassistants.view.widget.NoScrollGridView;

/**
 * @Description: 添加或修改招领信息
 * @author: yzx
 * @time: 2016-4-4 下午3:52:18
 */
@SuppressLint("SimpleDateFormat")
public class FindActivity extends BaseActivity implements OnClickListener,
		OnItemClickListener, OnItemLongClickListener {

	private ImageButton topBackIB;// 顶部返回按钮
	private ImageButton topSendBtn;// 顶部发送按钮
	private RelativeLayout itemsRL;// 物品信息
	private LinearLayout itemsLL;// 物品信息
	private RelativeLayout otherRL;// 其他信息
	private LinearLayout otherLL;// 其他信息
	private ImageView itemsImg;// 向上或向下箭头
	private ImageView otherImg;// 向上或向下箭头
	private MaterialEditText titleET;// 物品标题
	private MaterialBetterSpinner typeSp;// 物品类型
	private MaterialEditText describeET;// 物品描述
	private MaterialEditText placeET;// 丢失地点
	private MaterialEditText timeET;// 丢失时间
	private MaterialEditText phoneET;// 联系号码
	private List<ImageItem> picList;// 图片列表信息
	private NoScrollGridView picGV;// 图片列表

	private CircularLoadingDialog dialog;
	private String from;//
	private String findId;// 丢失物品id
	private boolean isNew;// 判断是否是新增
	private List<ImageView> imgList;//
	private List<LinearLayout> llList;//
	private List<Boolean> isOpenList;//
	private FindThing findInfo;// 失物信息
	private List<BmobFile> picFileList;// 图片文件列表
	private EditGridAdapter editAdapter;// 图片列表可编辑的适配器
	private AlertDialog albumDialog;// 选择图片来源
	private File tempFile;// 图片缓存
	private String imagePath;// 图片路径
	private SimpleDateFormat mFormatter = new SimpleDateFormat(
			"yyyy-MM-dd aa hh:mm");// 日期时间格式

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_find);
		init();
		initView();
		setListener();
		initData();
		initMaterialRipple();
	}

	/**
	 * 
	 * @Description: 初始化
	 */
	private void init() {
		from = getIntent().getStringExtra("from");
		if (CommonConstant.FROM_MYFINDACTIVITY.equals(from)) {// modify
			isNew = false;
			findInfo = (FindThing) getIntent().getSerializableExtra("findInfo");
		}
		if (CommonConstant.FROM_ANDFINDFRAGMENT.equals(from)) {// add
			isNew = true;
			findInfo = new FindThing();
		}
	}

	/**
	 * 
	 * @Description: 初始化控件
	 */
	@SuppressLint("ClickableViewAccessibility")
	private void initView() {
		dialog = new CircularLoadingDialog(this);
		itemsRL = (RelativeLayout) findViewById(R.id.lost_find_items_title_rl);
		otherRL = (RelativeLayout) findViewById(R.id.lost_find_other_title_rl);
		itemsLL = (LinearLayout) findViewById(R.id.lost_find_items_ll);
		otherLL = (LinearLayout) findViewById(R.id.lost_find_other_ll);
		itemsImg = (ImageView) findViewById(R.id.lost_find_items_title_arrow_img);
		otherImg = (ImageView) findViewById(R.id.lost_find_other_title_arrow_img);
		topBackIB = (ImageButton) findViewById(R.id.find_back_btn);
		topSendBtn = (ImageButton) findViewById(R.id.find_send_btn);

		titleET = (MaterialEditText) findViewById(R.id.lost_find_items_title_edit);
		typeSp = (MaterialBetterSpinner) findViewById(R.id.lost_find_items_type_spinner);
		describeET = (MaterialEditText) findViewById(R.id.lost_find_items_describe_edit);
		placeET = (MaterialEditText) findViewById(R.id.lost_find_other_place_edit);
		timeET = (MaterialEditText) findViewById(R.id.lost_find_other_time_edit);
		// 弹出日期时间选择
		timeET.setOnTouchListener(new OnTouchListener() {
			int touch_flag = 0;

			@SuppressLint("ClickableViewAccessibility")
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (v.getId()) {
				case R.id.lost_find_other_time_edit: {
					touch_flag++;
					if (touch_flag == 4) {
						pickDateTime();
						touch_flag = 0;
					}
					break;
				}
				default:
					break;
				}
				return false;
			}
		});
		phoneET = (MaterialEditText) findViewById(R.id.lost_find_other_phone_edit);
		picGV = (NoScrollGridView) findViewById(R.id.lost_find_items_pic_gv);
	}

	/**
	 * 
	 * @Description: 选择时间
	 */
	private void pickDateTime() {
		new SlideDateTimePicker.Builder(getSupportFragmentManager())
				.setListener(new SlideDateTimeListener() {

					@Override
					public void onDateTimeSet(Date date) {// 选择时间
						timeET.setText(mFormatter.format(date));
					}
				})
				.setInitialDate(new Date())
				.setMaxDate(new Date())
				.setIndicatorColor(
						getResources().getColor(R.color.actionbar_color))
				.build().show();
	}

	/**
	 * 
	 * @Description: 设置监听
	 */
	private void setListener() {
		topBackIB.setOnClickListener(this);
		topSendBtn.setOnClickListener(this);
		picGV.setOnItemClickListener(this);
		picGV.setOnItemLongClickListener(this);
	}

	/**
	 * 
	 * @Description: 初始化数据
	 */
	private void initData() {
		// 默认打开时候第一个选项为张开
		itemsLL.setVisibility(View.VISIBLE);
		itemsImg.setImageResource(R.drawable.arrow_up);
		llList = new ArrayList<LinearLayout>();
		llList.add(itemsLL);
		llList.add(otherLL);
		imgList = new ArrayList<ImageView>();
		imgList.add(itemsImg);
		imgList.add(otherImg);
		isOpenList = new ArrayList<Boolean>();
		isOpenList.add(true);
		isOpenList.add(false);
		picList = new ArrayList<ImageItem>();
		picFileList = new ArrayList<BmobFile>();
		editAdapter = new EditGridAdapter(FindActivity.this, picList);
		picGV.setAdapter(editAdapter);
		editAdapter.notifyDataSetChanged();
		if (isNew) {

		} else {
			initFindData();
		}
	}

	/**
	 * 
	 * @Description: 初始化丢失数据
	 */
	private void initFindData() {
		if (findInfo == null) {
			isNew = true;
		} else {
			findId = findInfo.getObjectId();
			titleET.setText(findInfo.getTitle());
			typeSp.setText(findInfo.getType());
			describeET.setText(findInfo.getDescribe());
			placeET.setText(findInfo.getPlace());
			timeET.setText(findInfo.getTime());
			phoneET.setText(findInfo.getPhone());
			picFileList = findInfo.getPicFileList();
			if (null == picFileList || 1 > picFileList.size()) {

			} else {
				for (BmobFile bmobFile : picFileList) {
					if (bmobFile != null) {
						ImageItem imageItem = new ImageItem();
						imageItem.setIsLocalPic(false);
						imageItem.setFileName(bmobFile.getFilename());
						imageItem.setImagePath(bmobFile
								.getFileUrl(FindActivity.this));
						picList.add(imageItem);
					}
				}
			}
		}
	}

	/**
	 * 
	 * @Description: 瓷砖特效
	 */
	private void initMaterialRipple() {
		// 设置Spinner的Adapter
		String[] list = getResources().getStringArray(R.array.lost_find_type);
		List<String> dataList = Arrays.asList(list);
		MyArrayAdapter adapter = new MyArrayAdapter(this, dataList);
		typeSp.setAdapter(adapter);
		describeET.setSingleLine(true);
		describeET.setSingleLineEllipsis();
		// 设置Padding
		titleET.setPaddings(DensityUtils.sp2px(this, 32), 0, 0, 0);
		typeSp.setPaddings(DensityUtils.sp2px(this, 32), 0, 0, 0);
		describeET.setPaddings(DensityUtils.sp2px(this, 32), 0, 0, 0);
		placeET.setPaddings(DensityUtils.sp2px(this, 32), 0, 0, 0);
		timeET.setPaddings(DensityUtils.sp2px(this, 32), 0, 0, 0);
		phoneET.setPaddings(DensityUtils.sp2px(this, 32), 0, 0, 0);
		// 设置验证信息
		phoneET.addValidator(new METValidator("请输入正确的联系号码格式~") {

			@Override
			public boolean isValid(@NonNull CharSequence text, boolean isEmpty) {
				String number = text.toString();
				if ("".equals(number) || VerifyUtils.checkPhone(number)) {
					return true;
				}
				return false;
			}
		});

		List<View> views = new ArrayList<View>();
		views.add(itemsRL);
		views.add(otherRL);
		for (View view : views) {
			// 动态特效
			MaterialRippleLayout
					.on(view)
					.rippleColor(
							Color.parseColor(CommonConstant.RIPPLE_COLOR_LITHT))
					.rippleAlpha(CommonConstant.RIPPLE_ALPHA).rippleHover(true)
					.create();
		}

	}

	/**
	 * 
	 * @Description: 按键监听
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.find_back_btn: {// 返回按钮
			finish();
			break;
		}
		case R.id.find_send_btn: {// 新建发送按钮
			dialog.show();
			addByType();
			break;
		}
		default:
			break;
		}
	}

	String title = "";
	String type = "";
	String describe = "";
	String place = "";
	String time = "";
	String phone = "";

	/**
	 * @Description: 根据类型添加失物信息
	 */
	private void addByType() {
		title = titleET.getText().toString();
		type = typeSp.getText().toString();
		describe = describeET.getText().toString();
		place = placeET.getText().toString();
		time = timeET.getText().toString();
		phone = phoneET.getText().toString();
		if (null == title || "".equals(title)) {
			dialog.dismiss();
			showToast("请输入标题~", false);
			openLinearLayoutByNull(false);
			titleET.requestFocus();
			return;
		}
		if (null == type || "".equals(type)) {
			dialog.dismiss();
			openLinearLayoutByNull(false);
			showToast("请输入类型~", false);
			return;
		}
		if (null == describe || "".equals(describe)) {
			dialog.dismiss();
			openLinearLayoutByNull(false);
			showToast("请输入详细描述~", false);
			describeET.requestFocus();
			return;
		}
		if (null == place || "".equals(place)) {
			dialog.dismiss();
			openLinearLayoutByNull(true);
			showToast("请输入地点~", false);
			placeET.requestFocus();
			return;
		}
		if (null == time || "".equals(time)) {
			dialog.dismiss();
			showToast("请输入时间~", false);
			openLinearLayoutByNull(true);
			timeET.requestFocus();
			return;
		}
		if (null == phone || "".equals(phone)) {
			dialog.dismiss();
			showToast("请输入联系号码~", false);
			openLinearLayoutByNull(true);
			phoneET.requestFocus();
			return;
		}
		if (!VerifyUtils.checkPhone(phone)) {
			dialog.dismiss();
			showToast("请输入正确的联系号码格式~", false);
			openLinearLayoutByNull(true);
			phoneET.requestFocus();
			return;
		}
		addLost();
	}

	/**
	 * @Description: 打开对应的LinearLayout
	 */
	private void openLinearLayoutByNull(boolean b) {
		if (b) {
			llList.get(0).setVisibility(View.GONE);
			imgList.get(0).setImageResource(R.drawable.arrow_down);
			llList.get(1).setVisibility(View.VISIBLE);
			imgList.get(1).setImageResource(R.drawable.arrow_up);
		} else {
			llList.get(1).setVisibility(View.GONE);
			imgList.get(1).setImageResource(R.drawable.arrow_down);
			llList.get(0).setVisibility(View.VISIBLE);
			imgList.get(0).setImageResource(R.drawable.arrow_up);
		}
	}

	/**
	 * @Description: 添加招领信息
	 */
	private void addLost() {
		findInfo.setTitle(title);
		findInfo.setType(type);
		findInfo.setDescribe(describe);
		findInfo.setPlace(place);
		findInfo.setTime(time);
		findInfo.setPhone(phone);
		findInfo.setUsername(GlobalParams.userInfo.getUsername());// 发布人信息
		findInfo.setUser(GlobalParams.userInfo);
		List<String> filePathList = new ArrayList<String>();
		for (ImageItem item : picList) {
			if ("".equals(item.getImagePath()) || null == item.getImagePath()
					|| !item.getIsLocalPic()) {

			} else {
				filePathList.add(item.getImagePath());
			}
		}
		String[] filePaths = (String[]) filePathList.toArray(new String[0]);
		// 无图片
		if (null == filePaths || 1 > filePaths.length) {
			findInfo.setPicFileList(picFileList);
			// 新增
			if (isNew) {

				findInfo.save(FindActivity.this, new SaveListener() {

					@Override
					public void onSuccess() {// 添加成功
						LogcatUtils.i("新增招领信息成功");
						dialog.dismiss();
						setResult(CommonConstant.RESULTCODE_NEW_FIND_OK);
						finish();
					}

					@Override
					public void onFailure(int code, String message) {
						LogcatUtils.e("新增招领信息失败：" + code + " " + message);
						dialog.dismiss();
						switch (code) {
						case 9010: {// 网络超时
							showToast("网络超时，请检查您的手机网络~", false);
							break;
						}
						case 9016: {// 无网络连接，请检查您的手机网络
							showToast("无网络连接，请检查您的手机网络~", false);
							break;
						}
						default: {
							showToast("新增招领信息失败，请重试~", false);
							break;
						}
						}
					}
				});
			} else {// 修改
				findInfo.update(FindActivity.this, findId,
						new UpdateListener() {

							@Override
							public void onSuccess() {// 修改成功
								LogcatUtils.i("修改招领信息成功");
								dialog.dismiss();
								setResult(CommonConstant.RESULTCODE_UPDATE_FIND_OK);
								finish();
							}

							@Override
							public void onFailure(int code, String message) {
								LogcatUtils.e("修改招领信息失败：" + code + " "
										+ message);
								dialog.dismiss();
								switch (code) {
								case 9010: {// 网络超时
									showToast("网络超时，请检查您的手机网络~", false);
									break;
								}
								case 9016: {// 无网络连接，请检查您的手机网络
									showToast("无网络连接，请检查您的手机网络~", false);
									break;
								}
								default: {
									showToast("修改招领信息失败，请重试~", false);
									break;
								}
								}
							}
						});
			}
		} else {// 有图片
			// 批量上传
			BmobProFile.getInstance(FindActivity.this).uploadBatch(filePaths,
					new UploadBatchListener() {

						@Override
						public void onError(int code, String message) {
							LogcatUtils.e("批量上传图片失败：" + code + " " + message);
							dialog.dismiss();
							switch (code) {
							case 9010: {// 网络超时
								showToast("网络超时，请检查您的手机网络~", false);
								break;
							}
							case 9016: {// 无网络连接，请检查您的手机网络
								showToast("无网络连接，请检查您的手机网络~", false);
								break;
							}
							default: {
								showToast("批量上传图片失败，请重试~", false);
								break;
							}
							}
						}

						@Override
						public void onSuccess(boolean isFinish,
								String[] fileNames, String[] urls,
								BmobFile[] files) {

							if (isFinish) {
								LogcatUtils.i("批量上传图片成功");
								for (int i = 0; i < files.length; i++) {
									picFileList.add(files[i]);
								}
								findInfo.setPicFileList(picFileList);
								if (isNew) {// 新增

									findInfo.save(FindActivity.this,
											new SaveListener() {

												@Override
												public void onSuccess() {// 添加成功
													LogcatUtils.i("新增招领信息成功");
													dialog.dismiss();
													setResult(CommonConstant.RESULTCODE_NEW_FIND_OK);
													finish();
												}

												@Override
												public void onFailure(int code,
														String message) {
													LogcatUtils.e("新增招领信息失败："
															+ code + " "
															+ message);
													dialog.dismiss();
													switch (code) {
													case 9010: {// 网络超时
														showToast(
																"网络超时，请检查您的手机网络~",
																false);
														break;
													}
													case 9016: {// 无网络连接，请检查您的手机网络
														showToast(
																"无网络连接，请检查您的手机网络~",
																false);
														break;
													}
													default: {
														showToast(
																"新增招领信息失败，请重试~",
																false);
														break;
													}
													}

												}
											});
								} else {// 修改
									findInfo.update(FindActivity.this, findId,
											new UpdateListener() {

												@Override
												public void onSuccess() {// 修改成功
													LogcatUtils.i("修改招领信息成功");
													dialog.dismiss();
													setResult(CommonConstant.RESULTCODE_UPDATE_FIND_OK);
													finish();
												}

												@Override
												public void onFailure(int code,
														String message) {
													LogcatUtils.e("修改招领信息失败："
															+ code + " "
															+ message);
													dialog.dismiss();
													switch (code) {
													case 9010: {// 网络超时
														showToast(
																"网络超时，请检查您的手机网络~",
																false);
														break;
													}
													case 9016: {// 无网络连接，请检查您的手机网络
														showToast(
																"无网络连接，请检查您的手机网络~",
																false);
														break;
													}
													default: {
														showToast(
																"修改招领信息失败，请重试~",
																false);
														break;
													}
													}
												}
											});
								}
							}
						}

						@Override
						public void onProgress(int curIndex, int curPercent,
								int total, int totalPercent) {

						}
					});
		}

	}

	/**
	 * @Description: 按键监听更改布局
	 */
	public void newLostOrFindClick(View v) {
		for (LinearLayout ll : llList) {
			ll.setVisibility(View.GONE);
		}
		for (ImageView img : imgList) {
			img.setImageResource(R.drawable.arrow_down);
		}
		switch (v.getId()) {
		case R.id.lost_find_items_title_rl: {// 物品信息
			if (isOpenList.get(0)) {
				isOpenList.set(0, false);
			} else {
				llList.get(0).setVisibility(View.VISIBLE);
				for (int i = 0; i < isOpenList.size(); i++) {
					isOpenList.set(i, false);
				}
				isOpenList.set(0, true);
				imgList.get(0).setImageResource(R.drawable.arrow_up);
			}
			break;
		}
		case R.id.lost_find_other_title_rl: {// 其他信息
			if (isOpenList.get(1)) {
				isOpenList.set(1, false);
			} else {
				llList.get(1).setVisibility(View.VISIBLE);
				for (int i = 0; i < isOpenList.size(); i++) {
					isOpenList.set(i, false);
				}
				isOpenList.set(1, true);
				imgList.get(1).setImageResource(R.drawable.arrow_up);
			}
			break;
		}
		}
	}

	/**
	 * 
	 * @Description: 列表长按监听
	 */
	@Override
	public boolean onItemLongClick(AdapterView<?> adapterView, View view,
			int position, long arg3) {
		if (position == picList.size()) {
			return false;
		} else {
			showDeleteDialog(position);
			return true;
		}
	}

	/**
	 * @Description: 弹出是否删除提示
	 */
	private void showDeleteDialog(final int position) {
		new SweetAlertDialog(FindActivity.this, SweetAlertDialog.WARNING_TYPE)
				.setTitleText("你确定删除该图片吗？")
				.setCancelText("取消")
				.setConfirmText("删除")
				.showCancelButton(true)
				.setCancelClickListener(null)
				.setConfirmClickListener(
						new SweetAlertDialog.OnSweetClickListener() {

							@Override
							public void onClick(

							SweetAlertDialog sweetAlertDialog) {// 删除图片
								deletePic(position);
								editAdapter.notifyDataSetChanged();
								sweetAlertDialog.dismiss();
							}

						}).show();
	}

	/**
	 * 
	 * @Description: 删除图片
	 */
	private void deletePic(int position) {
		ImageItem item = picList.get(position);
		if (item.getIsLocalPic()) {
			picList.remove(position);
		} else {
			picFileList.remove(position);
			picList.remove(position);
		}

	}

	/**
	 * 
	 * @Description: 列表点击监听
	 */
	@Override
	public void onItemClick(AdapterView<?> adapterView, View view,
			int position, long arg3) {
		if (position == picList.size()) {
			showAlbumDialog();// 打开菜单选择图片来源
		} else {
			String[] imagePaths = new String[picList.size()];
			for (int i = 0; i < picList.size(); i++) {
				if (picList.get(i).getIsLocalPic()) {
					imagePaths[i] = "file://" + picList.get(i).getImagePath();
				} else {
					imagePaths[i] = picList.get(i).getImagePath();
				}
			}
			loadLocalImage(position, imagePaths);
		}
	}

	/**
	 * 
	 * @Description: 加载本地的图片
	 * @param position
	 * @param imagePath
	 */
	private void loadLocalImage(int position, String[] imagePaths) {
		Intent intent = new Intent(FindActivity.this, ImagePagerActivity.class);
		intent.putExtra(ImagePagerActivity.IMAGE_URLS, imagePaths);
		intent.putExtra(ImagePagerActivity.IMAGE_INDEX, position);
		startActivity(intent);
	}

	/**
	 * 
	 * @Description: 从拍照获取
	 */
	private void getPicFromCamera() {
		imagePath = FileUtils.getImagePath();
		File f = new File(imagePath);
		if (f.exists()) {
			f.delete();
		}
		try {
			f.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Uri uri = Uri.fromFile(f);
		Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		camera.putExtra(MediaStore.EXTRA_OUTPUT, uri);
		startActivityForResult(camera, CommonConstant.REQUESTCODE_PHOTO_CAMERA);
	}

	/**
	 * 
	 * @Description: 弹框选择图片来源
	 */
	@SuppressLint("InflateParams")
	private void showAlbumDialog() {
		albumDialog = new AlertDialog.Builder(this).create();
		albumDialog.setCanceledOnTouchOutside(true);
		View v = LayoutInflater.from(this).inflate(
				R.layout.dialog_select_picture, null);
		albumDialog.show();
		albumDialog.setContentView(v);
		albumDialog.getWindow().setGravity(Gravity.CENTER);

		TextView albumPic = (TextView) v.findViewById(R.id.album_pic);
		TextView cameraPic = (TextView) v.findViewById(R.id.camera_pic);
		// 动态特效
		MaterialRippleLayout
				.on(albumPic)
				.rippleColor(Color.parseColor(CommonConstant.RIPPLE_COLOR_DARK))
				.rippleAlpha(CommonConstant.RIPPLE_ALPHA).rippleHover(true)
				.create();
		MaterialRippleLayout
				.on(cameraPic)
				.rippleColor(Color.parseColor(CommonConstant.RIPPLE_COLOR_DARK))
				.rippleAlpha(CommonConstant.RIPPLE_ALPHA).rippleHover(true)
				.create();
		albumPic.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				albumDialog.dismiss();
				getPicFromAlbum();
			}
		});
		cameraPic.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				albumDialog.dismiss();
				getPicFromCamera();
			}
		});
	}

	/**
	 * 
	 * @Description: 从相册获取
	 */
	private void getPicFromAlbum() {
		// 激活系统图库，选择一张图片
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType("image/*");
		startActivityForResult(intent, CommonConstant.REQUESTCODE_PHOTO_ALBUM);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			// 访问相册
			if (requestCode == CommonConstant.REQUESTCODE_PHOTO_ALBUM) {
				String fileName = null;
				if (data != null) {
					// 得到图片的全路径
					Uri uri = data.getData();
					ContentResolver cr = getContentResolver();
					Cursor cursor = cr.query(uri, null, null, null, null);
					if (cursor.moveToFirst()) {
						do {
							fileName = cursor.getString(cursor
									.getColumnIndex("_data"));
						} while (cursor.moveToNext());
					}
					tempFile = new File(fileName);
					if (tempFile.exists() && tempFile.length() > 0) {
						ImageItem albumPic = new ImageItem();
						albumPic.setIsLocalPic(true);
						albumPic.setImagePath(fileName);
						picList.add(albumPic);
						editAdapter.notifyDataSetChanged();
					}
				}

			}
			// 访问相机
			if (requestCode == CommonConstant.REQUESTCODE_PHOTO_CAMERA) {
				if (FileUtils.hasSdcard()) {
					Bitmap bitmap = ImageUtils.scale(
							BitmapFactory.decodeFile(imagePath), 0.7F, 0.7F);
					if (null == imagePath || "".equals(imagePath)) {

					} else {
						tempFile = new File(imagePath);
						if (tempFile.exists() && tempFile.length() > 0) {
							// 判断照片是否被旋转，如果旋转则旋转回0°
							int degree = ImageUtils.getBitmapDegree(imagePath);
							if (degree != 0) {
								bitmap = ImageUtils.rotateBitmapByDegree(
										bitmap, degree);
							}
							ImageUtils.toFile(bitmap, tempFile);
							ImageItem takePhoto = new ImageItem();
							takePhoto.setIsLocalPic(true);
							takePhoto.setImagePath(imagePath);
							picList.add(takePhoto);
							editAdapter.notifyDataSetChanged();
						} else {
						}
					}

				} else {
					showToast("未找到存储卡，无法存储照片！", false);
				}
			}

		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 
	 * @Description: Toast显示信息
	 */
	private void showToast(String message, Boolean isInfo) {
		if (isInfo) {
			ToastUtils.showInfoToast(this, message, R.id.find_content_ll);
		} else {
			ToastUtils.showAlertToast(this, message, R.id.find_content_ll);
		}

	}
}
